package com.example.sixthweek;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresPermission;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ShareActionProvider;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity{

    private static final String TAG = "myclick";
    public float dollarRate ;
    public float euroRate ;
    public float wonRate;
    Handler handler;
    TextView edit2;
    private  Timer timer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);//加载上次保存的汇率值
        SharedPreferences sharedPreferences = getSharedPreferences("myrate",Activity.MODE_PRIVATE);
        dollarRate = sharedPreferences.getFloat("dollar_Rate",0.1f);
        euroRate = sharedPreferences.getFloat("euro_Rate",0.2f);
        wonRate = sharedPreferences.getFloat("won_Rate",123.0f);
        Log.i(TAG, "onCreate: "+dollarRate);


//       handler = new Handler(){
//           @Override
//           public void handleMessage(@NonNull Message msg) {
//               if(msg.what==5){
//                   String str = (String)msg.obj;
//                   edit2 = findViewById(R.id.edit2);
//                   edit2.setText(str);
//               }
//               super.handleMessage(msg);
//           }
//       };





        Handler handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                if(msg.what== 1){
                    Bundle bundle = msg.getData();
                    dollarRate = bundle.getFloat("DollarRate");
                    euroRate = bundle.getFloat("EuroRate");
                    wonRate = bundle.getFloat("WonRate");
                }
                super.handleMessage(msg);
//            //获取td元素
////            Elements tds = doc.getElementsByTag("td");
////            for(Element td : tds){
////                Log.i(TAG, "run: td="+td.text());
////
////            }
////            for(int i=0;i < tds.size();i+=6){
////                Element td1 = tds.get(i);
////                Element td2 = tds.get(i+1);
////                String str1 = td1.text();
////                String val = td2.text();
////                Log.i(TAG, "run: "+ str1+"==>"+val);
////                Float v = 100f / Float.parseFloat(val) ;
////                Log.i(TAG, "run: rate="+v);
////                if(str1=="欧元"){
////                    Log.i(TAG, "run: eurorate="+val);
////                }
////                if(str1=="美元"){
////                    Log.i(TAG, "run: dollarrate="+val);
////                }
////                if(str1=="韩元"){
////                    Log.i(TAG, "run: wonrate="+val);
////                }
////            }

////            Element table = doc.getElementsByTag("table").first();
////            Element table = doc.selectFirst("table");
////            Element td = table.selectFirst("tr:nth-child(8)>td:nth-child(6)");
////            Log.i(TAG, "run: "+td.text());
////            Element td2 = doc.selectFirst("body > section > div > div > article > table > tbody > tr:nth-child(6) > td:nth-child(4)");
////            Log.i(TAG, "run: "+td2);


       // 获取网络数据


            }
        };

//       // 开启线程
//        Thread t = new Thread((Runnable) this);
//        t.start();
//
//
////        相当于Thread t2 = new Thread(new Runnable() {
////            @Override
////            public void run() {
////                //
////            }
////        });

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
//                try{
//                    URL url = null;
//                    url = new URL("https://www.usd-cny.com/bankofchina.htm");
//                    HttpURLConnection http = (HttpURLConnection) url.openConnection();
//                    InputStream in = http.getInputStream();
//                    String html = inputStream2String(in);
//                    Log.i(TAG, "run: html=" +html);
//
//                }catch (MalformedURLException e){
//                    e.printStackTrace();
//                }catch(IOException e) {
//                    e.printStackTrace();
//
//                }

                try {
                    Bundle bundle = new Bundle();
                    Document doc = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
                    String title = doc.title();
                    Log.i(TAG, "run: title="+title);

                    Elements trs = doc.getElementsByTag("tr");
                    for(Element tr: trs){
                        Elements tds = tr.getElementsByTag("td");
                        Log.i(TAG, "run: td.size="+tds.size());
                        if(tds.size()>0){
                            String td1 = tds.get(0).text();
                            String td2 = tds.get(5).text();
                            if(td1.equals("欧元")){
                                float a = 100f/Float.parseFloat(td2);
                                bundle.putFloat("EuroRate",a);
                                Log.i(TAG, "handleMessage: "+a);
                            }else if(td1.equals("美元")){
                                float b = 100f/Float.parseFloat(td2);
                                bundle.putFloat("DollarRate",b);
                                Log.i(TAG, "handleMessage: "+b);
                            }else if(td1.equals("韩元")){
                                float c = 100f/Float.parseFloat(td2);
                                bundle.putFloat("WonRate",c);
                                Log.i(TAG, "handleMessage: "+c);
                            }

                        }
                    }
                    Message msg = handler.obtainMessage(1);
                    msg.setData(bundle);
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        },0,86400000);

    }


    public void myclick(View btn){
         EditText edit1 = findViewById(R.id.edit1);
         String str0 = edit1.getText().toString();
         float num0 = Float.parseFloat(str0);
         float r = 0.0f;
        if(str0.length()==0){
            Toast.makeText(this,"请输入金额",Toast.LENGTH_SHORT).show();
           return;
        }
        if(btn.getId()==R.id.btn1){
               r = num0 * dollarRate;

        }
        if(btn.getId()==R.id.btn2){
                r = num0 * euroRate;

        }
        if(btn.getId()==R.id.btn3){
               r = num0 * wonRate;

        }
        edit2 = findViewById(R.id.edit2);
        edit2.setText("结果为："+r);

    }
    public void open(View btn){
        openConfig();

    }

    private void openConfig() {
        Log.i(TAG,"open: config");
        Intent intent = new Intent(this,ConfigActivity.class);
        intent.putExtra("dollar_key",dollarRate);
        intent.putExtra("euro_key",euroRate);
        intent.putExtra("won_key",wonRate);

        Log.i(TAG,"open:dollar_key="+dollarRate);
        Log.i(TAG, "open: euro_key="+euroRate);
        Log.i(TAG, "open: won_key="+wonRate);

        //startActivity(intent);

        startActivityForResult(intent,3);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 3 && resultCode == 6) {
        //汇率修改页面返回的数据
            Bundle bdl = data.getExtras();
            //拆分放入的数据项
            dollarRate = bdl.getFloat("key_dollar2");
            euroRate = bdl.getFloat("key_euro2");
            wonRate = bdl.getFloat("key_won2");
            SharedPreferences sp = getSharedPreferences("myrate",Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putFloat("dollar_Rate",dollarRate);
            editor.putFloat("euro_Rate",euroRate);
            editor.putFloat("won_Rate",wonRate);
            editor.apply();
        }
        super.onActivityResult(requestCode, resultCode, data);
//        }else if(requestCode==3&&resultCode==7){
//            //汇率修改页面返回的数据只包括美元（自己假设的 还可以假设无数个代回数据的情况 ）
//        }

        //保存新的数据到sp中


    }



//    @Override
//    public void run() {
//        Log.i(TAG, "run: Running....");
//        //do...
//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

//        //获取网络数据
////        URL url = null;
////        try{
////            url = new URL("https://www.usd-cny.com/bankofchina.htm");
////            HttpURLConnection http = (HttpURLConnection) url.openConnection();
////            InputStream in = http.getInputStream();
////            String html = inputStream2String(in);
////            Log.i(TAG, "run: html=" +html);
////
////
////        }catch (MalformedURLException e){
////            e.printStackTrace();
////        }catch(IOException e) {
////            e.printStackTrace();
////
////        }
//        try {
//            Document doc = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
//            String title = doc.title();
//            Log.i(TAG, "run: title="+title);
//            //获取td元素
////            Elements tds = doc.getElementsByTag("td");
////            for(Element td : tds){
////                Log.i(TAG, "run: td="+td.text());
////
////            }
////            for(int i=0;i < tds.size();i+=6){
////                Element td1 = tds.get(i);
////                Element td2 = tds.get(i+1);
////                String str1 = td1.text();
////                String val = td2.text();
////                Log.i(TAG, "run: "+ str1+"==>"+val);
////                Float v = 100f / Float.parseFloat(val) ;
////                Log.i(TAG, "run: rate="+v);
////                if(str1=="欧元"){
////                    Log.i(TAG, "run: eurorate="+val);
////                }
////                if(str1=="美元"){
////                    Log.i(TAG, "run: dollarrate="+val);
////                }
////                if(str1=="韩元"){
////                    Log.i(TAG, "run: wonrate="+val);
////                }
////            }
//            Elements trs = doc.getElementsByTag("tr");
//            for(Element tr: trs){
//                Elements tds = tr.getElementsByTag("td");
//                Log.i(TAG, "run: td.size="+tds.size());
//                if(tds.size()>0){
//                    String td1 = tds.get(0).text();
//                    String td2 = tds.get(5).text();
//                    if(td1=="欧元"){
//                        euroRate = 100f/Float.parseFloat(td2);
//                    }
//                    if(td1 =="美元"){
//                        dollarRate = 100f/Float.parseFloat(td2);
//                    }
//                    if(td1 =="韩元"){
//                        wonRate = 100f/Float.parseFloat(td2);
//                    }
//                }
//            }
////            Element table = doc.getElementsByTag("table").first();
////            Element table = doc.selectFirst("table");
////            Element td = table.selectFirst("tr:nth-child(8)>td:nth-child(6)");
////            Log.i(TAG, "run: "+td.text());
////            Element td2 = doc.selectFirst("body > section > div > div > article > table > tbody > tr:nth-child(6) > td:nth-child(4)");
////            Log.i(TAG, "run: "+td2);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        //返回消息给主线程
        //获取MSG对象，用于返回主线程
//        Message msg = handler.obtainMessage(5);
//        msg.obj = "Hello from run()";
//        handler.sendMessage(msg);
//        Message message = new Message();
//        message.what = 1;
//        handler.sendMessage(message);
//    }
//};



    private String inputStream2String(InputStream inputStream) throws  IOException{
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream, "gb2312");
        while(true){
            int rsz = in.read(buffer,0,buffer.length);
            if (rsz < 0){
                break;
            }
            out.append(buffer,0,rsz);
        }
        return out.toString();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu,menu);
        return true;
    }

   @Override
   public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.menu_set){
//事件处理代码
            openConfig();
        }
        return super.onOptionsItemSelected(item);
   }
}